﻿var sentences;
var sentences_count= 0;
var result = [];
var username;
var pwd;
var exit_flag;
var science_str;
var science_map = [];
var errorcolor ;
var alertcolor;
var importantcolor;
var strict_degree;
var start_time;
var sameword;
var sameword_str = [];
var science_jsonlist = {
    "不限领域": "all",
"哲学": "zx",
"心理": "xl",
"管理": "gl",
"法学": "fx",
"经济": "jj",
"体育": "ty",
"教育": "jy",
"新闻": "xw",
"语言": "yy",
"音乐": "yiny",
"地理": "dl",
"历史": "ls",
"数学": "sx",
"力学": "lx",
"化学": "hx",
"物理": "wl",
"材料": "cl",
"生物": "sw",
"植物": "zw",
"动物": "dw",
"天文": "tw",
"地质": "dz",
"大气": "dq",
"测绘": "ch",
"海洋": "hy",
"医学": "yx",
"药学": "yaox",
"遗传": "yc",
"农业": "ly",
"林学": "linx",
"园林": "yl",
"水产": "sc",
"自动化":"zdh",
"石油": "sy",
"煤炭": "mt",
"能源": "lr",
"冶金": "yj",
"电工": "dg",
"电力": "dianl",
"电子": "dianz",
"计算机": "jsj",
"机械": "jx",
"通信": "tx",
"计量": "jl",
"建筑": "jz",
"水利": "sl",
"航海": "hh",
"船舶": "cb",
"铁路": "tl",
"交通": "jt",
"航空航天": "xtxk",
"生态": "st",
"土壤": "tr",
"城市规划": "csgx",
}
function login(isauto) {
    var url;
    if (isauto)
    {
        if ($.cookie('fangcun_username') == null || $.cookie('fangcun_pwd') == null) {
            return;
        }

        //url = 'http://crm.ifuncun.cn//fc?method=check_user&data={"username":"' + $.cookie('fangcun_username') + '","pwd":"' + $.cookie('fangcun_pwd') + '","authedkey":"web"}';
        url = 'http://crm.ifuncun.cn:8080/funcun/plugInLoginVerification?userid=' + $.cookie('fangcun_username') + '&pwd=' + $.cookie('fangcun_pwd')+ '&call_time=' + Date.parse(new Date()) + '&authedkey=web';
        $("#username").val($.cookie('fangcun_username'));
        $("#pwd").val($.cookie('fangcun_pwd'));
    }
    else
    {
        if ($("#username").val().trim() == "" || $("#pwd").val().trim() == "")
        {
            $("#msgbox").html("错误:用户名或密码不能为空");
            return;
        }
        url = 'http://crm.ifuncun.cn:8080/funcun/plugInLoginVerification?userid=' + $("#username").val() + '&pwd=' + $("#pwd").val() + '&call_time=' + Date.parse(new Date()) + '&authedkey=web&ip=';
        //url = 'http://bg.ifuncun.cn//fc?method=check_user&data={"username":"' + $("#username").val() + '","pwd":"' + $("#pwd").val() + '","authedkey":"web"}';
    }
    $.ajax({
        url: url,
        type: "get",
        cookie: false,
        timeout: 3000,
        success: function (response) {
            if (response.ret_code == 0)
            {
                username = $("#username").val();
                pwd = $("#pwd").val();
                $("#login_div").hide();
                $("#fangcuncorrectmenus").show();
                $("#msgbox").html("");
                science_str = $.cookie('fangcun_science');
                if (science_str == null || science_str == "") science_str = "不限领域";
                if ($.cookie('errorcolor') == null) {
                    errorcolor = '#ffff00';
                }
                else {
                    errorcolor = $.cookie('errorcolor');
                }
                if ($.cookie('alertcolor') == null) {
                    alertcolor = '#ff0000';
                }
                else {
                    alertcolor = $.cookie('alertcolor');
                }
                if ($.cookie('importantcolor') == null) {
                    importantcolor = '#ff00ff';
                }
                else {
                    importantcolor = $.cookie('importantcolor');
                }
                if ($.cookie('strict_degree') == null) {
                    strict_degree= "l";
                }
                else {
                    strict_degree = $.cookie('strict_degree');
                }
                if ($.cookie('sameword') == null) {
                    sameword = "0";
                }
                else {
                    sameword = $.cookie('sameword');
                }
                if ($("#rem_pwd").is(':checked'))
                {
                    $.cookie('fangcun_username', username, { expires: 365 });
                    $.cookie('fangcun_pwd', pwd, { expires: 365 });
                }
                else
                {
                    $.cookie('fangcun_username', null);
                    $.cookie('fangcun_pwd', null);
                }
            }
            else 
            {
                $("#msgbox").html("错误:"+response.error_msg);
            }
        },
        error: function ()
        {
            $("#msgbox").html("错误:请检查您的网络");
        }
    });  
}
function correctpagssage(correct_type) {
    clearallmarks();
    Word.run(function (context) {
        // 将获取当前选定内容的命令插入队列，然后
        // 创建包含结果的代理范围对象。
        var correctcontent;
        start_time = new Date().getTime();
        $("#msgbox").html('');
        $('#suggestion').hide();
        switch (correct_type)
        {
            case 0:
                correctcontent = context.document.body;
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.getRange().getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
            case 1:
                correctcontent = context.document.getSelection();
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
            case 2:
                correctcontent = context.document.getSelection();
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.paragraphs.getFirst().getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
        }
        context.load(sentences, 'text');
        // 通过执行排队的命令来同步文档状态
        // 并返回承诺以表示任务完成。
        return context.sync()
            .then(function () {
                    if (sentences.items.length > 0) {
                        result = [];
                        sentences_count = 0;
                        exit_flag = false;
                        var thread_num = getthreadnumber();
                        if (thread_num != "") {
                            showprogressbar('正在校对中...');
                            for (var i = 0; i <= thread_num; i++) {
                                correctsentence_1(correct_type);
                            }
                        }
                        else {
                            $("#msgbox").html("错误:无法连接到云服务器,请检查您的网络！");
                        }
                    }
            })
    })
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
}
function correctsentence_1(correct_type)
{
    if (sentences_count >= sentences.items.length || exit_flag) return;
    var sel_index = sentences_count;
    var url = encodeURI("http://api.ifuncun.cn:8081/do?method=correct&userid=" + username + "&text=" + sentences.items[sel_index].text + "&domains=" + science_str + "&strict_degree=" + strict_degree);
    sentences_count++;
    $.ajax({
        url: url,
        type: "get",
        async: true,
        cookie: false,
        timeout:30000,
        success: function (response) {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count/ sentences.items.length * 100), width: "100%", height: "15px" });
            if (response != "") {
                result.push(response + "&_&" + sel_index);
            }
            else
            {
                result.push(" &_&" + sel_index);
            }
            if (result.length == sentences.items.length) {
                addfangcunmarks(correct_type);
            }
            else {
                correctsentence_2(correct_type);
            }
        },
        error: function () {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count/ sentences.items.length * 100), width: "100%", height: "15px" });
            result.push(" &_&" + sel_index)
            if (result.length == sentences.items.length) {
                addfangcunmarks(correct_type);
            }
            else {
                correctsentence_2(correct_type);
            }
        }
    });  

}

function correctsentence_2(correct_type) {
    if (sentences_count >= sentences.items.length || exit_flag) return;
    var sel_index = sentences_count;
    var url = encodeURI("http://api.ifuncun.cn:8081/do?method=correct&userid=" + username + "&text=" + sentences.items[sel_index].text + "&domains=" + science_str + "&strict_degree=" + strict_degree);
    sentences_count++;
    $.ajax({
        url: url,
        type: "get",
        async: true,
        cookie: false,
        timeout: 30000,
        success: function (response) {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count/ sentences.items.length * 100), width: "100%",height:"15px" });
            if (response != "") {
                result.push(response + "&_&" + sel_index);
            }
            else
            {
                result.push(" &_&" + sel_index);
            }
            if (result.length == sentences.items.length) {
                addfangcunmarks(correct_type);
            }
            else {
                correctsentence_1(correct_type);
            }
        },
        error: function () {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count/ sentences.items.length * 100), width: "100%", height: "15px" });
            result.push(" &_&" + sel_index);
            if (result.length == sentences.items.length) {
                addfangcunmarks(correct_type);
            }
            else {
                correctsentence_1(correct_type);
            }
        }
    });

}
function addfangcunmarks(correct_type) {
    Word.run(function (context) {
        // 将获取当前选定内容的命令插入队列，然后
        // 创建包含结果的代理范围对象。
        $("#progressbar").hide();
        var correctcontent;
        switch (correct_type) {
            case 0:
                correctcontent = context.document.body;
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.getRange().getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
            case 1:
                correctcontent = context.document.getSelection();
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
            case 2:
                correctcontent = context.document.getSelection();
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    sentences = correctcontent.paragraphs.getFirst().getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
                }
                break;
        }
        context.load(sentences, 'text');
        var error_rangs = [];
        var search_indexs = [];
        var error_infors = [];
        var error_sentences = [];
        return context.sync()
            .then(function (){
                for (var i = 0; i < result.length; i++)
                {
                    var error_infor = result[i].split("&_&");
                    if (error_infor[0].indexOf("right_word") > 0) {
                        var sentence_index = Number(error_infor[1]);
                        var error_jsons = JSON.parse(error_infor[0]);
                        error_jsons.sort(sorterrorjsons);
                        var flag_offset = error_jsons[0].offset + error_jsons[0].error_word.length;
                        for (var j = 0; j < error_jsons.length; j++)
                        {
                            if (j == 0 || error_jsons[j].offset >= flag_offset) {
                                var search_index = GetErrorWordIndex(sentences.items[sentence_index].text, error_jsons[j].error_word, error_jsons[j].offset);
                                var searchResults = sentences.items[sentence_index].search(error_jsons[j].error_word, { matchCase: true });
                                error_rangs.push(searchResults);
                                search_indexs.push(search_index);
                                error_infors.push(error_jsons[j]);
                                error_sentences.push(sentences.items[sentence_index].text);
                                flag_offset = error_jsons[j].offset + error_jsons[j].error_word.length;
                            }
                        }
                    }
                }
                for (var k = 0; k < error_rangs.length; k++) {
                    context.load(error_rangs[k], 'text,font');
                }
            })
            .then(context.sync)
            .then(function () {
                var error_types = [];
                for (var k = 0; k < search_indexs.length; k++) {
                    if (error_rangs[k].items[search_indexs[k]] != null) {
                        var fangcun_contrl = error_rangs[k].items[search_indexs[k]].insertContentControl();
                        if (error_infors[k].type.indexOf("敏感词") != -1) {
                            error_rangs[k].items[search_indexs[k]].font.highlightColor = importantcolor;
                            fangcun_contrl.title = "FangCunCorrect_敏感词:";
                        }
                        else {
                            if (error_infors[k].confidence > 0.85) {
                                error_rangs[k].items[search_indexs[k]].font.highlightColor = errorcolor;
                                fangcun_contrl.title = "FangCunCorrect_错 误:" + error_sentences[k];
                            }
                            else if (error_infors[k].confidence > 0.6) {
                                error_rangs[k].items[search_indexs[k]].font.highlightColor = alertcolor;
                                fangcun_contrl.title = "FangCunCorrect_警 告:" + error_sentences[k];
                            }
                        }
                        var error_infor = error_infors[k].right_word + "$_$" + error_infors[k].type;
                        //if (error_infor.length > 64) {
                        //    error_infor = error_infor.substring(0, 60) + '...';
                        //}
                        if (error_types.indexOf(error_infors[k].type) == -1) {
                            error_types.push(error_infors[k].type);
                        }
                        fangcun_contrl.tag = error_infor;
                    }
                }

                    var usedtime = (new Date().getTime() - start_time) / 1000;
                $("#msgbox").html("共用：" + Math.round(usedtime) + "秒<br />共发现：" + search_indexs.length+"处错误<br />共发现：" + error_types.length + "类型错误");
            })          
    })
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
}
function sorterrorjsons(a, b) {
    return a.offset - b.offset;
}
function GetErrorWordIndex(sentence_str, error_word, offset)
{
    var pos = sentence_str.indexOf(error_word);
    if (pos >= offset) {
        return 0;
    }
    else
    {
        var rval = 1;
        while (pos > -1)
        {
            pos = sentence_str.indexOf(error_word, pos + 1);
            if (pos >= offset) return rval;
            rval++;
        }
    }
}
function showsciencesetpage() {
    $("#fangcuncorrectmenus").hide();
    $('#suggestion').hide();
    $('#scisetpage').show();
    selectscience(science_str);
    var h = $(document).height() - $(window).height();
    $(document).scrollTop(h); 

}
function sciencegetall() {
    $('#scisettree').jstree().select_all();
    $('#scisettree').jstree().uncheck_node('all');

}
function scienceconfirm() {

    //var checkedNodes = $('#scisettree').jstree('get_selected', true)[0].text;
    $('#scisetpage').hide();
    $("#fangcuncorrectmenus").show();
    if (science_str == "") science_str = "不限领域";
    $.cookie('fangcun_science', science_str, { expires: 365 });
    $('#msgbox').html('');

}
function sciencecancle() {
    $('#scisetpage').hide();
    $("#fangcuncorrectmenus").show();
    $('#msgbox').html('');
    science_str = $.cookie('fangcun_science');
    if (science_str == null || science_str =="") science_str = "不限领域";
    $.cookie('fangcun_science', science_str, { expires: 365 });
}
function showprogressbar(title) {
    $('#progressbar_tilte').html(title);
    $('#progressbar').show();
    $("#progressbar").myProgress({ speed: 0, percent:0, width: "100%", height: "15px" });
    var h = $(document).height() - $(window).height();
    $(document).scrollTop(h); 
}
function cancel_progress()
{
    exit_flag = true;
    $('#progressbar').hide();
}
function scienceautoget()
{
      Word.run(function (context) {
        // 将获取当前选定内容的命令插入队列，然后
        // 创建包含结果的代理范围对象。
        var correctcontent= context.document.body;
        if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
            sentences = correctcontent.getRange().getTextRanges(["\r\n", ".", "。", "?", "？", "!", "！"], false);
        }
        context.load(sentences, 'text');
        // 通过执行排队的命令来同步文档状态
        // 并返回承诺以表示任务完成。
        sentences_count = 0;
        science_map = [];     
        return context.sync()
            .then(function () {
                if (sentences.items.length > 0) {
                    showprogressbar('正在判断中...');
                    $('#msgbox').html('');
                    if (sentences.items.length > 100)
                    {
                        autogetscience_1(100);
                    }
                    else
                    {
                        autogetscience_1(sentences.items.length);
                    }
                }
            })
    })
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
}
function autogetscience_1(all_num)
{
    var sel_index = sentences_count;
    var url = encodeURI("http://bg.ifuncun.cn:8081/do?method=judge_domains&userid=" + username + "&text=" + sentences.items[sel_index].text);
    sentences_count++;
    $.ajax({
        url: url,
        type: "get",
        async: true,
        cookie: false,
        timeout: 3000,
        success: function (response) {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count / all_num * 100), width: "100%", height: "15px" });
            if (response != "") {
                var science_jsons = JSON.parse(response);
                for (var i = 0; i < science_jsons.length; i++) {
                    updatascience_map(science_jsons[i]);
                }
            }
            if (sentences_count >= all_num) {
                getsciencestring();
            }
            else {
                autogetscience_2(all_num);
            }
        },
        error: function () {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count / all_num * 100), width: "100%", height: "15px" });
            if (sentences_count >= all_num) {
                getsciencestring();
            }
            else {
                autogetscience_2(all_num);
            }
        }
    });
}
function autogetscience_2(all_num)
{
    var sel_index = sentences_count;
    var url = encodeURI("http:/api.ifuncun.cn:8081/do?method=judge_domains&userid=" + username + "&text=" + sentences.items[sel_index].text);
    sentences_count++;
    $.ajax({
        url: url,
        type: "get",
        async: true,
        cookie: false,
        timeout: 3000,
        success: function (response) {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count / all_num * 100), width: "100%", height: "15px" });
            if (response != "") {
                var science_jsons = JSON.parse(response);
                for (var i = 0; i < science_jsons.length; i++) {
                    updatascience_map(science_jsons[i]);
                }
            }
            if (sentences_count >= all_num) {
                getsciencestring();

            }
            else {
                autogetscience_1(all_num);
            }
        },
        error: function () {
            $("#progressbar").myProgress({ speed: 0, percent: Math.round(sentences_count / all_num * 100), width: "100%", height: "15px" });
            if (sentences_count >= all_num) {
                getsciencestring();
            }
            else {
                autogetscience_1(all_num);
            }
        }
    });

}
function updatascience_map(sci_j)
{
    for (var sci in science_map)
    {
        if (science_map[sci].domain == sci_j.domain)
        {
            science_map[sci].weight = science_map[sci].weight + sci_j.weight;
            return;
        }
    }
    science_map.push(sci_j);
}
function getthreadnumber()
{
    var url = encodeURI("http://api.ifuncun.cn:8081/do?method=get_thread_number");
    var reval = "";
    $.ajax({
        url: url,
        type: "get",
        async: false,
        cookie: false,
        timeout: 5000, 
        success: function (response) {
            reval=response;
        }
    });
    return reval;
}
function getsciencestring()
{
    var lastvalue;
    $("#progressbar").hide();
    if ($.isEmptyObject(science_map))
    {
        selectscience("不限领域");
    }
    else
    {
        var lastval = science_map[0].weight;
        var sciencestring = "";
        science_map.sort(sortsciencejson);
        for (var sci in science_map)
        {
            if (science_map[sci].weight >= lastval / 2) {
                sciencestring = sciencestring + science_map[sci].domain + "|";
                lastval = science_map[sci].weight;
            }
            else {
                break;
            }
        }
        selectscience(sciencestring);
    }
}

function selectscience(sci_str)
{
    var sci_all = sci_str.split('|');
    $('#scisettree').jstree().uncheck_all();
    for (var i = 0; i < sci_all.length; i++)
    {
        $('#scisettree').jstree().check_node(science_jsonlist[sci_all[i]]);
    }
}
function sortsciencejson(a, b) {
    return b.weight - a.weight;
}
function findnexterror(is_next)
{
    $("#msgbox").html('');
    Word.run(function (context) {

        var fangcunerrors = context.document.body.contentControls;
        var sel_range = context.document.getSelection();
        context.load(fangcunerrors, 'text,tag,title');
        var location_relations = [];
        return context.sync()
            .then(function () {
                for (var i = 0; i < fangcunerrors.items.length; i++) {
                    if (Office.context.requirements.isSetSupported('WordApi', '1.3') && fangcunerrors.items[i].title.indexOf("FangCunCorrect")!=-1) {
                        var i_content_rang = fangcunerrors.items[i].getRange(Word.RangeLocation.start);
                        var location_relation = sel_range.compareLocationWith(i_content_rang);
                        location_relations.push(location_relation);
                    }
                }
            })
            .then(context.sync)
            .then(function () {
                if (is_next) {
                    for (var i = 0; i < location_relations.length; i++) {
                        if (location_relations[i].m_value == Word.LocationRelation.before) {
                            fangcunerrors.items[i].select(Word.SelectionMode.start);
                            break;
                        }
                    }
                }
                else
                {
                    for (var i = location_relations.length - 1; i >= 0; i--) {
                        if (location_relations[i].m_value == Word.LocationRelation.after) {
                            fangcunerrors.items[i].select(Word.SelectionMode.start);
                            break;
                        }
                    }
                }

            })
    })
}
function DocumentSelectionChanged(eventArgs) {
    Word.run(function (context) {
        var sel_content_ctrl = context.document.getSelection().parentContentControl;
        context.load(sel_content_ctrl, 'title,text,tag');
        var location_relations = [];
        return context.sync()
            .then(function () {
                if (sel_content_ctrl.title.indexOf("FangCunCorrect") != -1) {
                    showsuggetion(sel_content_ctrl.tag, sel_content_ctrl.text);
                    $("#fangcuncorrectmenus").hide();
                }
                else
                {
                    showsuggetion('','');
                }
            })
           
    })
        .catch(function (error) {
            showsuggetion('','');
        });
}
function showsuggetion(tag_str,content_text)
{
    if (tag_str =='') {
        //$('#suggestion').hide();
        //$("#errortable_div").hide();
        //$("#fangcun_pie_div").hide();
        if ($("#suggestion").is(":visible") == true) {
            $('#suggestion').hide();
            if ($("#errortable_div").is(":visible") == false) {
                $("#fangcuncorrectmenus").show();
            }
            else {
                $('#showfangcunmenus_btn6').show();
            }
        }
    }
    else
    {
        $("#msgbox").html('');
        $('#suggestion').show();
        $('#scisetpage').hide();
        $('#dic_div').hide();
        $("#fangcun_pie_div").hide();
        $("#usersetting_div").hide();
        $("#advancesetting_div").hide();
        $("#about_div").hide();
        $('#showfangcunmenus_btn6').hide();
        var errorword_infor = tag_str.split("$_$");
        var right_words = errorword_infor[0].split("|");
        $('#error_type').html(errorword_infor[1]);
        $('#sug_listbox').empty();
        $('#sug_listbox').attr("name", content_text);
        for (var i = 0; i < right_words.length; i++)
        {
            $("#sug_listbox").append("<option >" + right_words[i] + "</option>");
        }
        if (right_words[0]!="") {
            $("#sug_listbox").get(0).selectedIndex = 0;
            $("#recorrectselect_btn").show();
            $("#recorrectall_btn").show();
        }
        else {
            $("#recorrectselect_btn").hide();
            $("#recorrectall_btn").hide();
        }
    }
}
function correctselectword(correct_type)
{
    Word.run(function (context) {
        var sel_content_ctrl = context.document.getSelection().parentContentControl;
        var fangcunerrors = context.document.body.contentControls;
        context.load(fangcunerrors, 'title,text,tag');
        context.load(sel_content_ctrl, 'title,text,tag');
        return context.sync()
            .then(function () {
                switch (correct_type) {
                    case 0:
                        sel_content_ctrl.insertText($("#sug_listbox").find("option:selected").text(), Word.InsertLocation.replace);
                        sel_content_ctrl.getRange(Word.RangeLocation.content).font.highlightColor = null;
                        sel_content_ctrl.delete(true);
                        addwordtodic("错词词典", false, $('#sug_listbox').attr("name"), $("#sug_listbox").find("option:selected").text(), sel_content_ctrl.title.substring(19));
                        break;
                    case 1:
                        addwordtodic("正词词典", false, $('#sug_listbox').attr("name"), "", sel_content_ctrl.title.substring(19))
                        if (sameword == "1" && sameword_str.indexOf($('#sug_listbox').attr("name")) != -1) {

                            for (var i = 0; i < fangcunerrors.items.length; i++) {
                                if (fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1 && fangcunerrors.items[i].text == $('#sug_listbox').attr("name")) {
                                    fangcunerrors.items[i].getRange(Word.RangeLocation.content).font.highlightColor = null;
                                    fangcunerrors.items[i].delete(true);
                                }
                            }
                        }
                        else {
                            sel_content_ctrl.getRange(Word.RangeLocation.content).font.highlightColor = null;
                            sel_content_ctrl.delete(true);
                        }
                        if (sameword_str.indexOf($('#sug_listbox').attr("name")) == -1) {
                            sameword_str.push($('#sug_listbox').attr("name"));
                        }
                        break;
                    case 2:
                        for (var i = 0; i < fangcunerrors.items.length; i++) {
                            if (fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1 && fangcunerrors.items[i].text == $('#sug_listbox').attr("name")) {
                                fangcunerrors.items[i].insertText($("#sug_listbox").find("option:selected").text(), Word.InsertLocation.replace);
                                fangcunerrors.items[i].getRange(Word.RangeLocation.content).font.highlightColor = null;
                                fangcunerrors.items[i].delete(true);
                            }

                        }
                        break;
                    case 3:
                        sel_content_ctrl.delete();
                        context.document.getSelection().insertText($("#myanswer").val(), Word.InsertLocation.end);
                        break;
                }
            })
            .then(context.sync)
            .then(function () {
                if ($("#errortable_div").is(":visible") == true) {
                    showerrortable();
                }
            })
    })
        .catch(function (error) {
            showsuggetion('');
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
}

function showfangcunmenus() {
   $("#msgbox").html('');
   $('#suggestion').hide();
    $('#dic_div').hide();
    $('#errortable_div').hide();
    $("#fangcun_pie_div").hide();
    $("#usersetting_div").hide();
    $("#advancesetting_div").hide();
    $("#about_div").hide();
    $("#fangcuncorrectmenus").show();
}
function clearselectmark() {
    Word.run(function (context) {

        var sel_content_ctrl = context.document.getSelection().parentContentControl;
        context.load(sel_content_ctrl, 'text,tag');
        return context.sync()
            .then(function () {
                sel_content_ctrl.getRange(Word.RangeLocation.content).font.highlightColor = null;
                sel_content_ctrl.delete(true);
            })
    })
}
function clearallmarks()
{
    $("#msgbox").html('');
    Word.run(function (context) {

        var fangcunerrors = context.document.body.contentControls;
        context.load(fangcunerrors, 'title,text,tag');
        return context.sync()
            .then(function () {
                for (var i = 0; i < fangcunerrors.items.length; i++) {
                    if (fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1) {
                        fangcunerrors.items[i].getRange(Word.RangeLocation.content).font.highlightColor = null;
                        fangcunerrors.items[i].delete(true);
                    }

                }
            })

    })
}
function addrightworddic()
{
    $("#msgbox").html('');
    $("#fangcuncorrectmenus").hide();
    $('#dic_div').show();
    $('#dic_div').attr("title", "正词词典");
    $("#dic_lable1").show();
    $("#dic_lable1").html('正词：<input type="text" id="dic_input1" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable2").hide();
    $("#dic_lable3").show();
    $("#dic_lable3").html('语境:<textarea id="dic_input3" style="height: 15px; width: 200px; margin: 0px 0 10px 10px;height:60px;vertical-align:middle;"></textarea>');
    $('#dic_input1').val('');
    $('#dic_input2').val('');
    $('#dic_input3').val('');
    $('#dic_input4').val('');
    queryword();
}
function addwrongworddic()
{
    $("#msgbox").html('');
    $("#fangcuncorrectmenus").hide();
    $('#dic_div').show();
    $('#dic_div').attr("title", "错词词典");
    $("#dic_lable1").show();
    $("#dic_lable1").html('错词：<input type="text" id="dic_input1" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable2").show();
    $("#dic_lable2").html('正词：<input type="text" id="dic_input2" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable3").show();
    $("#dic_lable3").html('语境:<textarea id="dic_input3" style="height: 15px; width: 200px; margin: 0px 0 10px 10px;height:60px;vertical-align:middle;"></textarea>');
    $('#dic_input1').val('');
    $('#dic_input2').val('');
    $('#dic_input3').val('');
    $('#dic_input4').val('');
    queryword();
}

function addimportantworddic()
{
    $("#msgbox").html('');
    $("#fangcuncorrectmenus").hide();
    $('#dic_div').show();
    $('#dic_div').attr("title", "重点监控");
    $("#dic_lable1").show();
    $("#dic_lable1").html('重点词：<input type="text" id="dic_input1" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable2").hide();
    $("#dic_lable3").hide();
    $('#dic_input1').val('');
    $('#dic_input2').val('');
    $('#dic_input3').val('');
    $('#dic_input4').val('');
    queryword();
}
function addvipworddic()
{
    $("#msgbox").html('');
    $("#fangcuncorrectmenus").hide();
    $('#dic_div').show();
    $('#dic_div').attr("title", "重要人物");
    $("#dic_lable1").show();
    $("#dic_lable1").html('姓名：<input type="text" id="dic_input1" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable2").show();
    $("#dic_lable2").html('排名：<input type="text" id="dic_input2" style="height: 15px; width: 200px; margin: 0px 0 10px 0;" />');
    $("#dic_lable3").show();
    $("#dic_lable3").html('职务:<textarea id="dic_input3" style="height: 15px; width: 200px; margin: 0px 0 10px 10px;height:60px;vertical-align:middle;"></textarea><div>多个用","分开</div>');
    $('#dic_input1').val('');
    $('#dic_input2').val('');
    $('#dic_input3').val('');
    $('#dic_input4').val('');
    queryword();
}
function modifyword() {
    var id = $("#dic_table").jqGrid('getGridParam', 'selrow');
    if (id != null) {
        var selrow = $("#dic_table").jqGrid('getRowData', id);
        var web_url;
        var flag_success = false;
        switch ($('#dic_div').attr('title')) {
            case "正词词典":
                if ($("#dic_input1").val() != '') {
                    web_url = 'http://crm.ifuncun.cn:8080/funcun/modifyDict_rightWords?user_code=' + username + '&right_word=' + selrow.right_word + '&context=' + selrow.context + '&new_right_word=' + $("#dic_input1").val() + '&new_context=' + $("#dic_input3").val();
                    flag_success = true;
                }
                else {

                    $("#msgbox").html('正词不能为空！');
                    flag_success = false;
                }
                break;
            case "错词词典":
                if ($("#dic_input1").val()!= '' && $("#dic_input2").val()!= '') {
                    web_url = 'http://crm.ifuncun.cn:8080/funcun/modifyDict_wrongWords?user_code=' + username + '&wrong_word=' + selrow.wrong_word + '&right_word=' + selrow.right_word + '&context=' + selrow.context + '&new_wrong_word=' + $("#dic_input1").val() + '&new_right_word=' + $("#dic_input2").val() + '&new_context=' + $("#dic_input3").val();
                    flag_success = true;
                }
                else {
                    $("#msgbox").html('错词和正词不能为空！');
                    flag_success = false;
                }
                break;
            case "重点监控":
                if ($("#dic_input1").val()!= '') {
                    web_url = 'http://crm.ifuncun.cn:8080/funcun/modifyDict_specialWords?user_code=' + username + '&special_word=' + selrow.special_word + '&new_special_word=' + $("#dic_input1").val();
                    flag_success = true;
                }
                else {
                    $("#msgbox").html('重点词不能为空！');
                    flag_success = false;
                }
                break;
            case "重要人物":
                if ($("#dic_input1").val() != '' || $("#dic_input2").val() != '' || $("#dic_input3").val() != '') {
                    web_url = 'http://crm.ifuncun.cn:8080/funcun/modifyDict_importantFigure?user_code=' + username + '&name=' + selrow.name + '&title=' + selrow.title + '&rank=' + selrow.rank + '&new_name=' + $("#dic_input1").val() + '&new_title=' + $("#dic_input3").val() + '&new_rank=' + $("#dic_input2").val();
                    flag_success = true;
                }
                else {
                    flag_success = false;
                    $("#msgbox").html('姓名、排名、职务不能为空！');
                }
                break;
        }
        if (flag_success) {
            $.ajax({
                url: encodeURI(web_url),
                type: "get",
                async: false,
                cookie: false,
                timeout: 3000,
                success: function (response) {
                    $("#msgbox").html(response.return_msg);
                    $('#dic_input4').val($('#dic_input1').val());
                    $('#dic_input1').val('');
                    $('#dic_input2').val('');
                    $('#dic_input3').val('');
                    queryword();

                },
                error: function () {
                    flag_success = false;
                    $("#msgbox").html('无法连接到云服务器！');
                }
            });
        }
    }
    else
    {
        $("#msgbox").html('请先选择要修改的数据！');
    }
    
}
function deleteword()
{
    var id = $("#dic_table").jqGrid('getGridParam', 'selrow');
    if (id != null) {
        var selrow = $("#dic_table").jqGrid('getRowData', id);
        var web_url;
        switch ($('#dic_div').attr('title')) {
            case "正词词典":
                web_url = 'http://crm.ifuncun.cn:8080/funcun/deleteDict_rightWords?user_code=' + username + '&right_word=' + selrow.right_word + '&context=' + selrow.context;
                break;
            case "错词词典":
                web_url = 'http://crm.ifuncun.cn:8080/funcun/deleteDict_wrongWords?user_code=' + username + '&wrong_word=' + selrow.wrong_word + '&right_word=' + selrow.right_word + '&context=' + selrow.context ;
                break;
            case "重点监控":
                web_url = 'http://crm.ifuncun.cn:8080/funcun/deleteDict_specialWords?user_code=' + username + '&special_word=' + selrow.special_word ;
                break;
            case "重要人物":
                web_url = 'http://crm.ifuncun.cn:8080/funcun/deleteDict_importantFigure?user_code=' + username + '&name=' + selrow.name + '&rank=' + selrow.rank ;
                break;
        }
            $.ajax({
                url: encodeURI(web_url),
                type: "get",
                async: false,
                cookie: false,
                timeout: 3000,
                success: function (response) {
                    if (response.return_code == 0) {
                        $("#dic_table").delRowData(id);
                    }
                    $("#msgbox").html(response.return_msg);
                    $('#dic_input4').val($('#dic_input1').val());
                    $('#dic_input1').val('');
                    $('#dic_input2').val('');
                    $('#dic_input3').val('');

                },
                error: function () {
                    $("#msgbox").html('无法连接到云服务器！');
                }
            });
    }
    else {
        $("#msgbox").html('请先选择要删除的数据！');
    }
}
function addwordtodic(word_type,is_showmsg,input1,input2,input3)
{
    var web_url = "";
    var flag_success;
    $("#msgbox").html('');
    switch (word_type) {
        case "正词词典":
            if (input1 != '') {
                web_url = 'http://crm.ifuncun.cn:8080/funcun/uploadDict_rightWords?user_code=' + username + '&right_word=' + input1 + '&context=' + input3;
                flag_success = true;
            }
            else
            {
                if (is_showmsg) {
                    $("#msgbox").html('正词不能为空！');
                }
                flag_success = false;
            }
            break;
        case "错词词典":
            if (input1 != '' && input2 != '') {
                web_url = 'http://crm.ifuncun.cn:8080/funcun/uploadDict_wrongWords?user_code=' + username + '&wrong_word=' + input1 + '&right_word=' + input2 + '&context=' + input3;
                flag_success = true;
            }
            else {
                if (is_showmsg) {
                    $("#msgbox").html('错词和正词不能为空！');
                }
                flag_success = false;
            }
            break;
        case "重点监控":
            if (input1 != '') {
                web_url = 'http://crm.ifuncun.cn:8080/funcun/uploadDict_specialWords?user_code=' + username + '&special_word=' + input1;
                flag_success = true;
            }
            else {
                if (is_showmsg) {
                    $("#msgbox").html('重点词不能为空！');
                }
                flag_success = false;
            }
            break;
        case "重要人物":
            if (input1 != ''|| input2 != '' || input3 != '') {
                web_url = 'http://crm.ifuncun.cn:8080/funcun/uploadDict_importantFigure?user_code=' + username + '&name=' + input1 + '&title=' + input3 + '&rank=' + input2;
                flag_success = true;
            }
            else {
                $("#msgbox").html('姓名、排名、职务不能为空！');
                flag_success = false;
            }
            break;
    }
    if (flag_success)
    {
        flag_success = false;
        $.ajax({
            url: encodeURI(web_url),
            type: "get",
            async: false,
            cookie: false,
            timeout: 3000,
            success: function (response) {
                if (response.return_code == 0) {
                    flag_success = true;
                    $('#dic_input4').val($('#dic_input1').val());
                    $('#dic_input1').val('');
                    $('#dic_input2').val('');
                    $('#dic_input3').val('');
                    queryword();
                }
                else
                {
                    flag_success = false;
                }
                if (is_showmsg) {
                    $("#msgbox").html(response.return_msg);
                }

            },
            error: function () {
                flag_success = false;
                $("#msgbox").html('无法连接到云服务器！');
            }
        });
    }
    return flag_success;
}
function queryword()
{
  $("#dic_table").jqGrid('GridUnload');
 switch ($('#dic_div').attr('title')) {
        case "正词词典":
            $("#dic_table").jqGrid(
                {
                    url: encodeURI('http://crm.ifuncun.cn:8080/funcun/getDict_rightWords?user_code=' + username + '&word=' + $('#dic_input4').val()+ '&page_no=-1'),
                    datatype: "json",//请求数据返回的类型。可选json,xml,txt
                    colNames: ['正词', '语境', '添加时间'],//jqGrid的列显示名字
                    colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                        { name: 'right_word', index: 'right_word',align: 'center', width: $(window).width() * 0.2},
                        { name: 'context', index: "context", align: 'center',width: $(window).width() * 0.37 },
                        { name: 'add_time', index: 'add_time',align: 'center', width: $(window).width() * 0.3 },
                    ],
                    loadonce:true,
                    rowNum:10,//一页显示多少条
                    pager: '#page_div',
                    sortname: 'add_time',//初始化的时候排序的字段
                    sortorder: "desc",//排序方式,可选desc,asc
                    mtype: "get",//向后台请求数据的ajax的类型。可选post,get
                    viewrecords: true,
                    caption: "正词词典"//表格的标题名字
                });
            break;
        case "错词词典":
            $("#dic_table").jqGrid(
                {
                    url: encodeURI('http://crm.ifuncun.cn:8080/funcun/getDict_wrongWords?user_code=' + username + '&word=' + $('#dic_input4').val()+ '&page_no=-1'),
                    datatype: "json",//请求数据返回的类型。可选json,xml,txt
                    colNames: ['错词','正词', '语境', '添加时间'],//jqGrid的列显示名字
                    colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                        { name: 'wrong_word', index: 'wrong_word', align: 'center',width: $(window).width() * 0.15 },
                        { name: 'right_word', index: 'right_word', align: 'center',width: $(window).width() * 0.15 },
                        { name: 'context', index: "context", align: 'center',width: $(window).width() * 0.27 },
                        { name: 'add_time', index: 'add_time', align: 'center',width: $(window).width() * 0.3 }
                    ],
                    loadonce:true,
                    rowNum: 10,//一页显示多少条
                    pager: '#page_div',
                    sortname: 'add_time',//初始化的时候排序的字段
                    sortorder: "desc",//排序方式,可选desc,asc
                    mtype: "get",//向后台请求数据的ajax的类型。可选post,get
                    viewrecords: true,
                    caption: "错词词典"//表格的标题名字
                });
            break;
        case "重点监控":
            $("#dic_table").jqGrid(
                {
                    url: encodeURI('http://crm.ifuncun.cn:8080/funcun/getDict_specialWords?user_code=' + username + '&word=' + $('#dic_input4').val()+ '&page_no=-1'),
                    datatype: "json",//请求数据返回的类型。可选json,xml,txt
                    colNames: ['重点词', '添加时间'],//jqGrid的列显示名字
                    colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                        { name: 'special_word', index: 'special_word',align: 'center', width: $(window).width() * 0.37 },
                        { name: 'add_time', index: 'add_time', align: 'center',width: $(window).width() * 0.5 }
                    ],
                    loadonce:true,
                    rowNum: 10,//一页显示多少条
                    pager: '#page_div',
                    sortname: 'add_time',//初始化的时候排序的字段
                    sortorder: "desc",//排序方式,可选desc,asc
                    mtype: "get",//向后台请求数据的ajax的类型。可选post,get
                    viewrecords: true,
                    caption: "重点监控库"//表格的标题名字
                });
            break;
        case "重要人物":
            $("#dic_table").jqGrid(
                {
                    url: encodeURI( 'http://crm.ifuncun.cn:8080/funcun/getDict_importantFigure?user_code=' + username + '&word=' + $('#dic_input4').val()+ '&page_no=-1'),
                    datatype: "json",//请求数据返回的类型。可选json,xml,txt
                    colNames: ['姓名', '职务','排名'],//jqGrid的列显示名字
                    colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                        { name: 'name', index: 'name', align: 'center',width: $(window).width() * 0.35 },
                        { name: 'title', index: "title",align: 'center', width: $(window).width() * 0.35 },
                        { name: 'rank', index: "rank",align: 'center', width: $(window).width() * 0.17 },   
                    ],
                    loadonce:true,
                    rowNum: 10,//一页显示多少条
                    pager: '#page_div',
                    sortname: 'add_time',//初始化的时候排序的字段
                    sortorder: "desc",//排序方式,可选desc,asc
                    mtype: "get",//向后台请求数据的ajax的类型。可选post,get
                    viewrecords: true,
                    caption: "重要人物库"//表格的标题名字
                });
            break;
    }
}
function showerrortable() {
    $("#msgbox").html('');
    $('#showfangcunmenus_btn6').show();
    $("#fangcuncorrectmenus").hide();
    $("#errortable_div").show();
    $("#error_table").jqGrid('GridUnload');
    $("#error_table").jqGrid(
        {
            datatype: "local",//请求数据返回的类型。可选json,xml,txt
            colNames: ['错误原因', '错词', '修改建议', '原句'],//jqGrid的列显示名字
            colModel: [ //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
                { name: 'error_type', index: 'error_type', align: 'center', width: $(window).width() * 0.4 },
                { name: 'error_word', index: "error_word", align: 'center', width: $(window).width() * 0.2 },
                { name: 'suggestion', index: "suggestion", align: 'center', width: $(window).width() * 0.27 },
                { name: 'content', index: "content", align: 'center', width: $(window).width() * 0.1 },
            ],
            mtype: "get",//向后台请求数据的ajax的类型。可选post,get
            viewrecords: true,
            caption: "勘误表",//表格的标题名字
            onSelectRow: function (ids) { //单击选择行  
                $("#msgbox").html('');
                Word.run(function (context) {
                    var fangcun_ctrl = [];
                    var fangcunerrors = context.document.body.contentControls;
                    var sel_range = context.document.getSelection();
                    context.load(fangcunerrors, 'text,tag,title');
                    return context.sync()
                        .then(function () {

                            for (var i = 0; i < fangcunerrors.items.length; i++) {
                                if ( fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1) {
                                    fangcun_ctrl.push(fangcunerrors.items[i]);
                                }
                            }
                            fangcun_ctrl[ids-1].select(Word.SelectionMode.start);
                        })
                })
            },  
        });
    $('#errortype_listbox').empty();
    var errortype_combox_str = '<option>所有错误</option>';
    Word.run(function (context) {
        var fangcunerrors = context.document.body.contentControls;
        context.load(fangcunerrors, 'title,text,tag');
        return context.sync()
            .then(function () {
                for (var i = 0; i < fangcunerrors.items.length; i++) {
                    if (fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1) {
                        var error_reason_str = fangcunerrors.items[i].tag.split("$_$")[1];
                        var right_wrods = fangcunerrors.items[i].tag.split("$_$")[0];
                        var errorword_json = '{"error_type":"' + error_reason_str + '","error_word":"' + fangcunerrors.items[i].text + '","suggestion":"' + right_wrods + '","content":"' + fangcunerrors.items[i].title.substring(19).trim() + '"}';
                        $("#error_table").jqGrid('addRowData', i + 1, JSON.parse(errorword_json.replace(/[\\\/\b\f\n\r\t]/g, '')));
                        if (errortype_combox_str.indexOf(error_reason_str) == -1) {
                            errortype_combox_str = errortype_combox_str + '<option>' + error_reason_str + '</option>';
                        }
                    }
                }
                $('#errortype_listbox').append(errortype_combox_str);
                $("#error_table").setGridParam().hideCol("content");  

            })

    })  

}
function error_tablechange()
{
    var sel_error_type = $("#errortype_listbox").find("option:selected").text();
    var error_tabe = $("#error_table").jqGrid("getRowData");
    for (var i = 0; i < error_tabe.length; i++)
    {
        if (sel_error_type == "所有错误") {
            $('#error_table').setRowData(i + 1, null, { display: 'table-row',  });
        }
        else {
            if (error_tabe[i].error_type == sel_error_type) {
                $('#error_table').setRowData(i + 1, null, { display: 'table-row' });
            }
            else {
                $('#error_table').setRowData(i + 1, null, { display: 'none' });
            }
        }
    }
}
function geterrortype(error_reason) {
    var type_str = "";
    if (error_reason.indexOf("推荐规范用词") != -1) {
        if (error_reason.indexOf("同音字错误") != -1) {
            type_str = "科技术语 - 同音字错误";
        }
        else if (error_reason.indexOf("形近字错误") != -1) {
            type_str = "科技术语 - 形近字错误";
        }
        else if (error_reason.indexOf("”台湾名称") != -1) {
            type_str = "科技术语 - 台湾名称";
        }
        else if (error_reason.indexOf("”是又称") != -1) {
            type_str = "科技术语 - 又称";
        }
        else if (error_reason.indexOf("”是曾称") != -1) {
            type_str = "科技术语 - 曾称";
        }
        else if (error_reason.indexOf("拼写错误") != -1) {
            type_str = "科技术语 - 拼写错误";
        }
        else if (error_reason.indexOf("漏字错误") != -1) {
            type_str = "科技术语 - 漏字错误";
        }
        else if (error_reason.indexOf("多字错误") != -1) {
            type_str = "科技术语 - 多字错误";
        }
        else {
            type_str = "科技术语 - 其他";
        }
    }
    else {
        if (error_reason.indexOf("同音字错误") != -1) {
            type_str = "普通词汇 - 同音字错误";
        }
        else if (error_reason.indexOf("形近字错误") != -1) {
            type_str = "普通词汇 - 形近字错误";
        }
        else if (error_reason.indexOf("”规范名称") != -1) {
            type_str = "普通词汇 - 非规范名称";
        }
        else if (error_reason.indexOf("非首选词") != -1) {
            type_str = "普通词汇 - 非首选词";
        }
        else {
            type_str = "普通词汇 - 其他";
        }
    }
    return type_str;
}
function exportreport() {
    Word.run(function (context) {
        var myNewDoc;
        if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
            myNewDoc = context.application.createDocument();
            context.load(myNewDoc, 'saved');
        }
        return context.sync()
            .then(function () {
                var error_table_data = $('#error_table').getRowData();
                for (var i = 0; i < error_table_data.length; i++) {
                    var error_sentence = (i+1).toString() + '、原句:' + error_table_data[i].content + '\n' + '错词:' + error_table_data[i].error_word + '\n' + '修改建议:' + error_table_data[i].suggestion + '\n';
                    myNewDoc.body.insertText(error_sentence, Word.InsertLocation.end);
                }
                if (Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                    myNewDoc.save();
                }
            })

    })  
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                $("#msgbox").html("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
}
function usersetting() {
    $("#fangcuncorrectmenus").hide();
    $("#usersetting_div").show();
    $("#changepwd").html("修改用户密码请访问:<br/>http://bg.ifuncun.cn//User/modpass/u/" + username);
}
function logout()
{
    $.cookie('fangcun_username', null);
    $.cookie('fangcun_pwd', null);
    $("#msgbox").html('');
    $("#usersetting_div").hide();
    $("#fangcuncorrectmenus").hide();
    $("#login_div").show();
    $("#username").val("");
    $("#pwd").val("");
    username = "";

}
function showerrorstatis()
{
    var label = [];
    var data = [];
    var errorstatis_jsons = [];
    Word.run(function (context) {
        var fangcunerrors = context.document.body.contentControls;
        context.load(fangcunerrors, 'title,text,tag');
        return context.sync()
            .then(function () {
                for (var i = 0; i < fangcunerrors.items.length; i++) {
                    if (fangcunerrors.items[i].title.indexOf("FangCunCorrect") != -1) {
                        var error_reason_str = geterrortype(fangcunerrors.items[i].tag.split("$_$")[1]);
                        if (label.indexOf(error_reason_str) == -1) {
                            label.push(error_reason_str);
                            data.push(1);
                        }
                        else {
                            data[label.indexOf(error_reason_str)] = data[label.indexOf(error_reason_str)] + 1;
                        }
                    }
                }
                for (var j = 0; j < label.length; j++) {
                    var errorstatis_str = '{"label":"' + label[j] + '","data":"' + data[j] + '"}';
                    errorstatis_jsons.push(JSON.parse(errorstatis_str));
                }
                if (errorstatis_jsons.length > 0) {
                    $("#msgbox").html('');
                    $("#fangcuncorrectmenus").hide();
                    $("#fangcun_pie_div").show();
                    var h = $(document).height() - $(window).height();
                    $(document).scrollTop(h); 
                    $.plot($("#fangcun_pie"), errorstatis_jsons, {
                        series: {
                            pie: {
                                show: true,
                            },
                        },
                        legend: {
                            labelFormatter: formatter,
                            show: true,
                            position: "sw",
                            
                        }
                    });   
                }
            })
    })  
}
function formatter(label, series) {
    return '<div style="font-size:10pt;padding:2px;color:black;">' + label + "：" + + series.percent.toFixed(2) + '%</div>';
}
function advancesetting() {
    $("#msgbox").html('');
    $("#fangcuncorrectmenus").hide();
    $("#advancesetting_div").show();
    if (sameword == 1) {
        $("#samewordcorrect").attr("checked", true);
    }
    else {
        $("#samewordcorrect").attr("checked", false);
    }
    $('#colorbox1').css('background-color', errorcolor);
    $('#colorbox1').attr("title", errorcolor);
    $('#colorbox2').css('background-color', alertcolor);
    $('#colorbox2').attr("title", alertcolor);
    $('#colorbox3').css('background-color', importantcolor);
    $('#colorbox3').attr("title", importantcolor);
    if (strict_degree == 'l') {
        $('#l_radio').attr('checked', true)
    }
    else
    {
        $('#h_radio').attr('checked', true)
    }

}
function showcolorselector(index)
{
    $('#colorselector1').hide();
    $('#colorselector2').hide();
    $('#colorselector3').hide();
    $('#colorselector' + index).show("slow");

}
function sethighlightcolor(colorbox)
{
    var colorboxindex = 1;
    if ($("#colorselector1").is(":visible") == true) {
        colorboxindex = 1;
    }
    else if ($("#colorselector2").is(":visible") == true) {
        colorboxindex = 2;
    }
    else {
        colorboxindex = 3;
    }
    $('#colorbox' + colorboxindex).css('background-color', colorbox);
    $('#colorbox' + colorboxindex).attr("title",colorbox);
    $('#colorselector' + colorboxindex).hide("slow");
}
function advancesettingconfirm()
{
    if ($("#samewordcorrect").is(':checked')) {
        $.cookie('sameword', '1', { expires: 365 });
        sameword = 1;
    }
    else {
        $.cookie('sameword', null);
        sameword = 0;
    }
    errorcolor = $(colorbox1).attr("title");
    $.cookie('errorcolor', errorcolor, { expires: 365 });
    alertcolor = $(colorbox2).attr("title");
    $.cookie('alertcolor', alertcolor, { expires: 365 });
    importantcolor = $(colorbox3).attr("title");
    $.cookie('importantcolor', importantcolor, { expires: 365 });
    if ($('#l_radio').is(':checked')) {
        strict_degree = "l";
    }
    else
    {
        strict_degree = "h";
    }
    $.cookie('strict_degree', strict_degree, { expires: 365 });
    showfangcunmenus();
}
function showabout() {
    $("#fangcuncorrectmenus").hide();
    $("#about_div").show();
}
(function () {
    // 每次加载新页面时都必须运行初始化函数
    Office.initialize = function (reason) {
        $(document).ready(function () {
            if (!Office.context.requirements.isSetSupported('WordApi', '1.3')) {
                $("#msgbox").html("当前Word版本不支持本插件！");  
            }
            else
            {
                login(true);
                $('#scisettree')
                    // listen for event
                    .on('changed.jstree', function (e, data) {
                        var i, j, r = [];
                        if (data.selected.length > 0) {
                            if (data.instance.get_node(data.selected[data.selected.length - 1]).text == "不限领域") {
                                for (i = 0, j = data.selected.length - 1; i < j; i++) {
                                    data.instance.uncheck_node(data.selected[i]);
                                }
                                data.instance.check_node('all');
                                r.push('不限领域');
                            }
                            else {
                                for (i = 0, j = data.selected.length; i < j; i++) {
                                    if (data.instance.get_node(data.selected[i]).text == "不限领域") {
                                        data.instance.uncheck_node('all');
                                    }
                                    else {
                                        if (data.instance.get_node(data.selected[i]).children.length <= 0) {
                                            r.push(data.instance.get_node(data.selected[i]).text);
                                        }
                                    }
                                }
                            }
                            science_str = r.join('|');
                            $('#msgbox').html('所选领域:' + r.join('|'));
                        }
                        else {
                            $('#msgbox').html("");
                        }
                    })
                    .jstree({
                        "plugins": ["checkbox"],
                        "core": {
                            "themes": {
                                "icons": false
                            }
                        },
                    });
                $('#scisettree').jstree().open_all();
                Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, DocumentSelectionChanged);
            }
           
        });
    };
})();
